package com.lzh.healthCode.utils;

import com.alibaba.fastjson.JSONObject;
import com.lzh.healthCode.business.entity.CjInfoBean;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/**
 * @author suYanLong
 * @date 2022年07月20日 14:51
 */
public class BeanUtils {

    public static JSONObject getBeanToJson(CjInfoBean cjInfoBean) {
        JSONObject result = new JSONObject();
        Class<? extends CjInfoBean> aClass = cjInfoBean.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(cjInfoBean);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            if (!StringUtils.isEmpty(value)) { // 排除空值的字段
                result.put(name.toLowerCase(), value); // 字段小写
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // 测试
        CjInfoBean cjInfoBean = new CjInfoBean();
        cjInfoBean.setBJCRXM("11111111111111");

        JSONObject beanToJson = getBeanToJson(cjInfoBean);
        System.out.println(beanToJson.toJSONString());
    }

}
